package cn.jiangjiesheng.bootstrap.integration.datapool;

import cn.jiangjiesheng.bootstrap.integration.datapool.params.DataPoolResult;
import cn.jiangjiesheng.bootstrap.integration.datapool.params.ReqActionParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ReadService {

    @Autowired
    @Qualifier("jdbcTemplateForPaas")
    private JdbcTemplate jdbcTemplate;

    public DataPoolResult read(ReqActionParam.ReadActionParam readActionParam) {
        String sql = String.format("select %s from ent_%s_datapool_%s ORDER BY id LIMIT %s, %s",
                readActionParam.getSelectClause(),
                readActionParam.getEntId(),
                readActionParam.getTableId(),
                readActionParam.getOffset(),
                readActionParam.getLimit()
        );
        return DataPoolResult.builder()
                .list(jdbcTemplate.queryForList(sql))
                .total(getCount(readActionParam))
                .limit(readActionParam.getLimit())
                .offset(readActionParam.getOffset())
                .build();
    }


    private Integer getCount(ReqActionParam.ReadActionParam readActionParam) {
        String sql = String.format("select count(1) from ent_%s_datapool_%s",
                readActionParam.getEntId(),
                readActionParam.getTableId()
        );
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }
}
